/**
 * DB配置
 * {
 *  dbSource:{
 *     name: "?",
 *     target: '?'
 *  },
 *  tableSource:{
 *    name: "?",
 *    target: '?'
 *  }
 * }
 * @author xiufu.wang
 */

const DataSource = require('nedb')
const path = require('path');
const { nextTick } = require('process');
const { createResonseError, createResonseSuccess } = require('./util')

const db = new DataSource({ filename: path.resolve(__dirname, '../../code-gen-db-db.db') });
db.loadDatabase()
/**
 * 参考 https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
 */
let executeAsap;
try {
    executeAsap = setImmediate;
} catch (e) {
    executeAsap = process.nextTick;
}

/**
 * post /api/code-gen/data-source/find
 * @param {*} req 
 * @param {*} res 
 */
exports.find = function (req, res) {
    db.findOne({}, function (err, docs) {
        res.json(createResonseSuccess(null, docs))
    })
}

exports.save = function (req, res) {
    const { data } = req.body || {}
    if (!data) {
        res.json(createResonseError('保存失败! 接口参数错误', data))
        return
    }
    //清除所有记录
    db.remove({}, { multi: true }, function (err) {
        if (err) {
            res.json(createResonseError('保存失败!' + err.message, data))
        } else {
            executeAsap(() => {
                db.insert(data, function (err, newDocs) {
                    if (err) {
                        res.json(createResonseError('保存失败!' + err.message, data))
                    } else {
                        res.json(createResonseSuccess('保存成功!', newDocs))
                    }
                });
            })
        }

    });
}

exports.baseRouterUrl = '/mock/api/code-gen/db/'
